﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Serious.SweetConfig
{
	/// <summary>
	/// Wrapper around Xml content to transform
	/// </summary>
	public class ParameterisedXml
	{
		private readonly XDocument _xmlContent;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="xmlContent">Source XDocument instance to transform</param>
		public ParameterisedXml(XDocument xmlContent)
		{
			_xmlContent = xmlContent;
		}

		/// <summary>
		/// Trnasforms the constent replacing the specified parameters
		/// </summary>
		/// <param name="parameters">ParameterList instance</param>
		/// <returns>Transformed XmlDocument instance</returns>
		public XDocument Transform(ParameterList parameters)
		{
			if (parameters == null)
			{
				throw new ArgumentNullException("parameters");
			}

			var result = new XDocument(_xmlContent);

			foreach(var parameter in parameters)
			{
				var matches = (IEnumerable<object>)result.XPathEvaluate(parameter.Match);
				
				foreach(object node in matches)
				{
					if (node is XAttribute)
					{
						((XAttribute)node).Value = parameter.Value;
					}

					if (node is XElement)
					{
						((XElement)node).ReplaceWith(XElement.Parse(parameter.Value));
					}
				}
			}

			return result;
		}
	}
}
